package com.joekai.base_library.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.core.content.FileProvider;

import com.joekai.base_library.BaseApp;

import java.io.File;

/**
 * author:  JoeKai
 * date: 2022/7/14 09:59
 * content：
 */
public class ApkUtil {
    private static ApkUtil mInstance;

    public static ApkUtil getInstance() {
        if (mInstance == null) {
            synchronized (ApkUtil.class) {
                if (mInstance == null) {
                    mInstance = new ApkUtil();
                }
            }
        }
        return mInstance;
    }

    public void install(Activity activity, File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean hasInstallPermission = activity.getPackageManager().canRequestPackageInstalls();
            if (!hasInstallPermission) {
                requestInstallPermission(activity);
            } else {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//这一句必须加，不然闪退
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                Uri uri = FileProvider.getUriForFile(activity, "com.ruirong.chefang.fileprovider", file);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                activity.startActivity(intent);
            }
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            } else {
                Uri uri = FileProvider.getUriForFile(activity, "com.ruirong.chefang.fileprovider", file);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(intent);
        }
    }

    // 提示设置权限对话框 ，根据选择项，是否跳转到权限设置页面
    private void requestInstallPermission(Activity activity) {
        Uri packageURI = Uri.parse("package:" + activity.getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        activity.startActivityForResult(intent, 5);
    }

    public File newFile( String fileName) {
        return new File(BaseApp.getInstance().getExternalCacheDir(), fileName + ".apk");

    }
}
